<?php
/**--------------------
 * Date: 2018/2/5
 * FileName:UserInfo.php  用户中心,登录后继承ApiBase
 * ProjectName:ZhiShiRongYao
 * -------------------- */


namespace app\api\controller;


use app\api\ApiBase;
use think\Db;

class UserInfo extends ApiBase
{

    /**
     * 获取用户信息
     *
     * @throws \think\exception\DbException
     * @return  string
     */
    public function getInfo()
    {
        $userInfo = Db::name('user')
                      ->field('id,grad_name,count_changshu,count_wins,exp')
                      ->where('id', $this->user_info['id'])
                      ->find();
        if ($userInfo) {
            //todo 提供计算经验的方法
            $userInfo['next_exp'] = 10000;
            if ((int)$userInfo['count_wins'] === 0) {
                $userInfo['win_rate'] = 0;
            } else {
                $userInfo['win_rate'] = (int)$userInfo['count_wins'] / (int)$userInfo['count_wins'];
            }
            $subs     = Db::name('knowledge_subject')
                          ->where('parent_id', 0)
                          ->select();
            $logs     = Db::name('user_answer_question')
                          ->alias('u')
                          ->field('subject_cate_id,remark,name,count(*) as num')
                          ->join('knowledge_subject k', 'k.id=u.subject_cate_id')
                          ->where([
                                      'user_id'     => $this->user_info['id'],
                                      'k.parent_id' => 0
                                  ])
                          ->group('subject_cate_id')
                          ->select();
            $names    = [];
            $data     = [];
            $log_list = [];
            foreach ($logs as $l) {

                $log_list[$l['subject_cate_id']] = $l;
            }


            foreach ($subs as $item) {
                if (isset($log_list[$item['id']])) {
                    $names[] = $item['name'];
                    $data[]  = $log_list[$item['id']]['num'];
                } else {
                    $names[] = $item['name'];
                    $data[]  = 0;
                }
            }
            $max_subs = $names[array_search(max($data), $data)];
            $min_subs = $names[array_search(min($data), $data)];
            $userInfo['canvas'] = [
                'names'    => $names,
                'data'     => $data,
                'max_subs' => $max_subs,
                'min_subs' => $min_subs,
            ];
            return $this->json_success('ok', $userInfo);
        }
        return $this->json_error('客户端错误');

    }
}